package com.abbas.abchat.dao.impl;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;

import com.abbas.abchat.dao.ChatMsgDao;
import com.abbas.abchat.db.Sqlite;
import com.abbas.abchat.entity.ChatMsg;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author abbas
 * @description: TODO
 * @date 2022/4/14 16:56
 */
public class ChatMsgDaoImpl implements ChatMsgDao {

    private Context mContext;
    private SQLiteDatabase sqLiteDatabase;
    private String dbName;

    public ChatMsgDaoImpl(Context context,String dbName) {
        this.mContext = context;
        this.dbName = dbName;
        //TODO: 找半天 结果是数据库名搞错了
        sqLiteDatabase = new Sqlite(context,Sqlite.DB_NAME,null,1).getWritableDatabase();
    }

    @SuppressLint("Range")
    @Override
    public List<ChatMsg> findAll() throws Exception {
        List<ChatMsg> msg = new ArrayList<>();
        Cursor cursor = sqLiteDatabase.query(dbName, null, null, null, null, null, null, null);
        while (cursor.moveToNext()){
            ChatMsg chatMsg = new ChatMsg();
            chatMsg.setId(cursor.getInt(cursor.getColumnIndex(ChatMsg.ID)));
            chatMsg.setContent(cursor.getString(cursor.getColumnIndex(ChatMsg.CONTENT)));
            chatMsg.setDate(cursor.getString(cursor.getColumnIndex(ChatMsg.DATE)));
            chatMsg.setpId(cursor.getInt(cursor.getColumnIndex(ChatMsg.P_ID)));
            chatMsg.setType(cursor.getInt(cursor.getColumnIndex(ChatMsg.TYPE)));
            msg.add(chatMsg);
        }
        cursor.close();
        return msg;
    }

    @Override
    public ChatMsg findById(int _id) throws Exception {
        return null;
    }

    @Override
    public long insert(ChatMsg entity){
        ContentValues contentValues = new ContentValues();
        if (!TextUtils.isEmpty(entity.getContent())){
            contentValues.put(ChatMsg.CONTENT,entity.getContent());
        }
        if (!TextUtils.isEmpty(entity.getDate())){
            contentValues.put(ChatMsg.DATE,entity.getDate());
        }
        if (!TextUtils.isEmpty(String.valueOf(entity.getpId()))){
            contentValues.put(ChatMsg.P_ID,String.valueOf(entity.getpId()));
        }
        if (!TextUtils.isEmpty(String.valueOf(entity.getType()))){
            contentValues.put(ChatMsg.TYPE,String.valueOf(entity.getType()));
        }
        return sqLiteDatabase.insert(dbName, null, contentValues);
    }

    @Override
    public int deleteById(int _id) throws Exception {
        return 0;
    }

    @Override
    public int updateById(ChatMsg entity) throws Exception {
        return 0;
    }
}
